var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken')
const { SECRET } = require('../../configs/index')
var md5 = require('md5');
const UserModel = require('../../models/UserModel')

/** 登录操作 */
router.post('/login', (req, res, next) => {
  const { username, password } = req.body  
  UserModel.findOne({
    username: username,
    password: md5(password)
  }).then(user => {
    if (user) {
      // 响应 token
      const token = jwt.sign({
        username: user.username,
        _id: user._id
      }, SECRET, {
        expiresIn: 60 * 60 * 24 * 7 // 7 天
      })
      res.json({
        code: '0000',
        msg: '登录成功',
        data: token
      })
    } else {
      res.json({
        code: '20002',
        mag: '用户名或者密码错误！',
        data: null
      })
    }
  }).catch(() => {
    res.json({
      code: '20003',
      mag: '登录失败',
      data: null
    })
  })
})

module.exports = router;
